#include "StdAfx.h"
#include "Background.h"
#include "HudMaterial.h"

Background::Background ()
{
}

Background::~Background ()
{
	glDeleteTextures(1, &m_textureId);
}

void Background::Init (char* path)
{
	// Texture
	int width, height, bpp;
	char* texBuffer = LoadTGA(path, &width, &height, &bpp);

	glGenTextures(1, &m_textureId);
	glBindTexture(GL_TEXTURE_2D, m_textureId);

	if (bpp == 24)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texBuffer);
	}
	else if (bpp == 32)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texBuffer);
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	
	glBindTexture(GL_TEXTURE_2D, 0);

	delete[] texBuffer;

	// Matrix
	m_matrix.SetIdentity();

	Matrix tmp;
	tmp.SetScale(2.0f);							m_matrix = m_matrix * tmp;
	tmp.SetTranslation(-1.0f, -1.0f, 0.0f);		m_matrix = m_matrix * tmp;
}

void Background::Render ()
{
	Shaders* shader = GetHudMaterial()->GetShader();
	GLuint boId = GetHudMaterial()->GetModel();
	
	glUseProgram(shader->program);
	glBindBuffer(GL_ARRAY_BUFFER, boId);

	if (shader->positionAttribute != -1)
	{
		glEnableVertexAttribArray(shader->positionAttribute);
		glVertexAttribPointer(shader->positionAttribute, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
	}
	if (shader->uvAttribute != -1)
	{
		glEnableVertexAttribArray(shader->uvAttribute);
		glVertexAttribPointer(shader->uvAttribute, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)( 3 * sizeof(float) ));
	}
	if (shader->textureUniform != -1)
	{
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, m_textureId);
		glUniform1i(shader->textureUniform, 0);
	}
	if (shader->matrixUniform != -1)
	{
		glUniformMatrix4fv(shader->matrixUniform, 1, GL_FALSE, (GLfloat*)m_matrix.m); 
	}
	if (shader->colorUniform != -1)
	{
		glUniform3f(shader->colorUniform, 1.0f, 1.0f, 1.0f);
	}

	glDrawArrays(GL_TRIANGLES, 0, 6);
	
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
}